﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Drawing;
using System.Drawing.Design;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using WenSkin.Controls;

namespace WenSkin.Design.Editor
{
    public class WenCollectionEditor : CollectionEditor
    {
        public WenCollectionEditor(Type type) : base(type)
        {
        }
        protected override CollectionForm CreateCollectionForm()
        {
            CollectionForm frm = base.CreateCollectionForm();
            if (frm.GetType().GetField("propertyBrowser", BindingFlags.NonPublic | BindingFlags.Instance) is FieldInfo propertyGridFielInfo)
            {
                (propertyGridFielInfo.GetValue(frm) as System.Windows.Forms.PropertyGrid).HelpVisible = true;
            }

            if (frm.GetType().GetField("listbox", BindingFlags.NonPublic | BindingFlags.Instance) is FieldInfo listboxFielInfo)
            {
                if (listboxFielInfo.GetValue(frm) is ListBox listBox)
                {
                    listBox.DrawMode = DrawMode.OwnerDrawFixed;
                    listBox.DrawItem += (s, e) =>
                    {
                        if (e.Index < 0)
                            return;
                        Graphics g = e.Graphics.SetGDIHigh();
                        Rectangle rec = e.Bounds;

                        int cut = (listBox.Items.Count.ToString().Length + 1) * 8;
                        Rectangle recStr = new Rectangle(cut, rec.Y + 1, rec.Width - cut, rec.Height - 2);
                        g.ResetClip();
                        g.FillRectangle(new SolidBrush(e.BackColor), recStr);

                        object value = listBox.Items[e.Index];

                        string text = value.GetType().GetProperty("Value").GetValue(value, null)?.ToString();

                        g.DrawString(text, e.Font, new SolidBrush(e.ForeColor), recStr);
                    };
                }
            }
            frm.Width = 600;
            frm.Height = 370;
            return frm;
        }
    }
}
